<template>
  <ContentDetailWrap @back="handleClose">
    <template #header>
      <BaseButton @click="go(-1)">{{ t('common.back') }}</BaseButton>
    </template>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-width="isMobile ? '100px' : '120px'"
      :class="isMobile ? 'mobile-check-form' : ''"
    >
      <el-form-item :label="t('inventory.available_qty')">
        <el-input v-model="form.available_qty" disabled />
      </el-form-item>

      <el-form-item :label="t('inventory.lock_qty')">
        <el-input v-model="form.lock_qty" disabled />
      </el-form-item>

      <el-form-item :label="t('inventory.checkQty')" prop="check_qty">
        <el-input v-model="form.check_qty" disabled style="width: 100%" />
      </el-form-item>

      <el-form-item :label="t('inventory.remark')" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="isMobile ? 4 : 3"
          :maxlength="300"
          :show-word-limit="true"
          :placeholder="t('inventory.remarkPlaceholder')"
          :disabled="actionType === 2"
        />
      </el-form-item>
    </el-form>
    <div :class="isMobile ? 'mobile-check-footer' : ''">
      <el-button @click="handleSubmit(3)">
        {{ t('common.reject') }}
      </el-button>
      <el-button type="primary" @click="handleSubmit(2)" :loading="submitting">
        {{ t('inventory.confirm') }}
      </el-button>
    </div>
  </ContentDetailWrap>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { submitCheckApi, getInfoApi } from '@/api/inventory'
import { useAppStore } from '@/store/modules/app'
import { hasPermission } from '@/utils'
import { useEventBus } from '@/hooks/event/useEventBus'

import { useTagsView } from '@/hooks/web/useTagsView'
const { closeCurrent } = useTagsView()
const { emit } = useEventBus()
const { t } = useI18n()
const router = useRouter()
const { go, push } = useRouter()
const { query } = useRoute()
// 移动端检测
const appStore = useAppStore()
const isMobile = computed(() => appStore.getMobile)

const formRef = ref<FormInstance>()
const submitting = ref(false)
const actionType = ref(2) // 1 校对 2 校对审核
// 表单数据结构
const form = ref({
  id: '',
  available_qty: '0',
  lock_qty: '0',
  check_qty: 0,
  remark: ''
})

// 表单验证规则
const rules = ref<FormRules>({
  check_qty: [
    {
      required: true,
      message: t('inventory.checkQtyRequired'),
      trigger: 'blur'
    },
    {
      validator: (_, value, callback) => {
        if (0 == value) {
          callback(new Error(t('inventory.checkQty') + '不能为0'))
        } else if (value < -(Number(form.value.available_qty) - Number(form.value.lock_qty))) {
          callback(
            new Error(
              t('inventory.checkQty') +
                '不能小于' +
                -(Number(form.value.available_qty) - Number(form.value.lock_qty))
            )
          )
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  remark: [
    {
      required: true,
      message: t('inventory.remarkRequired'),
      trigger: 'blur'
    }
  ]
})
const currentRow = ref<any>({})

const getInventoryInfo = async () => {
  const res = await getInfoApi(query.id as string)
  console.log(res, 'res')
  if (res) {
    currentRow.value = res.data
    console.log('hasPermission', hasPermission(['InventoryManagementCheck']))
    console.log('hasPermission2', hasPermission(['InventoryManagementCheck2']))

    if (
      currentRow.value.is_show_check_review_btn === 1 &&
      hasPermission(['InventoryManagementCheckReview'])
    ) {
      actionType.value = 2
      console.log(actionType.value, 'actionType.value')
    } else {
      handleClose()
      return false
    }
    form.value = {
      id: currentRow.value.id,
      available_qty: currentRow.value.available_qty,
      lock_qty: currentRow.value.lock_qty,
      check_qty: actionType.value === 1 ? 0 : Number(currentRow.value.check_qty),
      remark: actionType.value === 1 ? '' : currentRow.value.remark
    }
    console.log(form.value, 'form.value')
  }
}
onMounted(() => {
  // 弹窗关闭时重置状态
  submitting.value = false
  formRef.value?.resetFields()
  getInventoryInfo()
})

// 打开弹窗（父组件调用）
// type: 1 校对 2 校对审核
// const open = (row: any, type: number) => {
//   form.value = {
//     id: row.id,
//     available_qty: row.available_qty,
//     lock_qty: row.lock_qty,
//     check_qty: type === 1 ? 0 : Number(row.check_qty),
//     remark: type === 1 ? '' : row.remark
//   }
//   dialogVisible.value = true
//   actionType.value = type
// }

// 提交表单（修复后）
const handleSubmit = (num: Number) => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return

    submitting.value = true

    try {
      // 二次确认
      await ElMessageBox.confirm(t('inventory.confirmMessage'), t('common.tip'), {
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      })

      // 提交数据
      const params = {
        id: Number(form.value.id),
        check_qty: Number(form.value.check_qty),
        available_qty: Number(form.value.available_qty),
        lock_qty: Number(form.value.lock_qty),
        remark: form.value.remark,
        action_type: num
      }
      console.log(params, 'params')
      await submitCheckApi(params)
      emit('getInventoryList', 'add')
      ElMessage.success(t('common.operateSucMsg'))
      handleClose()
    } catch (error) {
      // 处理取消操作或提交错误
      if (error !== 'cancel') {
        ElMessage.error(t('inventory.submitError'))
      }
    } finally {
      // 无论成功失败都重置按钮状态
      submitting.value = false
    }
  })
}

const handleClose = () => {
  // 返回列表页关闭当前页
  closeCurrent()
  push('/warehouse/inventory-management')
}
</script>
